import React, { FC, useEffect, useState } from 'react';
import { Button, Space, Table, Modal, Popconfirm, App } from 'antd';
import { tableConfig } from './config';
import request from '@/config/request';
import _ from 'lodash';
import Create from './Create';
import './style.less';
import { dataProps } from './data';

const Application: FC = () => {
  const { message } = App.useApp();
  const [pageProps, setPageProps] = useState({
    pageNum: 1,
    pageSize: 10,
    siteName: 'skgm',
  });
  const [data, setData] = useState<dataProps[]>([]);
  const [open, setOpen] = useState<boolean | dataProps>(false);
  const [isRefresh, setIsRefresh] = useState({});

  useEffect(() => {
    request
      .get('/queryEduMessage', {
        params: pageProps,
      })
      .then((ret: any) => {
        if (ret.code === 0) {
          setData(_.flatten(ret.data));
        }
      });
  }, [pageProps, isRefresh]);

  const onCancel = () => setOpen(false);

  const del_al = (record: dataProps) => {
    request
      .get('/deleteEduMessage', {
        params: {
          id: record.id,
        },
      })
      .then((ret: any) => {
        if (ret.code === 0) {
          message.success(ret.msg);
          setIsRefresh({});
        } else {
          message.error(ret.msg);
        }
      });
  };

  return (
    <>
      <div className="al-top">
        <Button type="primary" onClick={() => setOpen(true)}>
          新增
        </Button>
      </div>
      <Table
        columns={tableConfig.map((item) => {
          const obj = { ...item };
          switch (obj.key) {
            case 'actions':
              obj.render = (text, record) => {
                return (
                  <Space>
                    <Popconfirm title="你确定要删除该项吗?" onConfirm={() => del_al(record)}>
                      <Button type="link" danger>
                        删除
                      </Button>
                    </Popconfirm>

                    <Button type="link" onClick={() => setOpen(record)}>
                      更新
                    </Button>
                  </Space>
                );
              };
              break;
            default:
              break;
          }
          return obj;
        })}
        dataSource={data}
        rowKey={'id'}
        pagination={{
          current: pageProps.pageNum,
          pageSize: pageProps.pageSize,
          onChange: (pageNum, pageSize) =>
            setPageProps((origin) => ({
              ...origin,
              pageNum,
              pageSize,
            })),
        }}
        scroll={{ x: 1500 }}
      />
      <Modal destroyOnClose open={!!open} footer={false} onCancel={onCancel} title="新增报名">
        <Create onCancel={onCancel} setIsRefresh={setIsRefresh} record={open} />
      </Modal>
    </>
  );
};

export default Application;
